package cn.cmcc.online.smsapi.sdk.net;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.Map;

import cn.cmcc.online.smsapi.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.cmcc.online.smsapi.sdk.Iservice.XyCallBack;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.entity.SysParamEntityManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.util.AESUtils;
import cn.cmcc.online.smsapi.sdk.net.util.RSAUtils;
import cn.cmcc.online.smsapi.sdk.net.util.Signaturer;
import cn.cmcc.online.smsapi.sdk.util.FileUtils;
import cn.cmcc.online.smsapi.sdk.util.RecordFunctionUtil;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
import cn.cmcc.online.smsapi.sdk.util.XyUtil;
import cn.cmcc.online.smsapi.util.UUIDUtils;

public class NewXyHttpRunnable extends BaseHttpRunnable{


   final static String TAG = "HTTP";
   public final static String ERROR_CODE_TOKEN_FAILED = "1";
   public final static String ERROR_CODE_PARE_ERR = "2";
   public final static String ERROR_CODE_SERVICE_ERR = "3";
   public static String RSA_PRV_KEY = null;

   /* KINGMAIL-49 huangzhiqiang 20170411 start */
   private Map<String,String> mExtendMap = null;
   /* KINGMAIL-49 huangzhiqiang 20170411 end */

//   String appkey;
   
	public NewXyHttpRunnable(String requestUrl,String reqeustContent,
			XyCallBack callBack,  boolean isLogin,boolean isCompress,Map<String,String> extendMap) {
		super(requestUrl, null, reqeustContent, isLogin, "", callBack, isCompress);
        /* KINGMAIL-49 huangzhiqiang 20170411 start */
        mExtendMap = extendMap;
        /* KINGMAIL-49 huangzhiqiang 20170411 end */
	}
	
/*	public NewXyHttpRunnable(String requestUrl,String reqeustContent,
			XyCallBack callBack,  boolean isLogin,boolean isCompress,Map<String,String> extendMap,String appkey) {
		super(requestUrl, null, reqeustContent, isLogin, "", callBack, isCompress);
		this.appkey = appkey;
	}
	
	*/
    @Override
    public void run() {
        HttpURLConnection http = null;
        OutputStream out = null;
        InputStream dis = null;
        try {
            http = getHttpURLConnection();
            if (http==null) {
            	  callBack(NetUtil.HTTP_THROWS_EXCEPTION, "http null");
            	  return ;
			}
            http.connect();
            out = http.getOutputStream();
            /*SDK-646 zhaojiangwei 20161122 start */
            if (out==null) {
          	  	callBack(NetUtil.HTTP_THROWS_EXCEPTION, "http out null");
          	  	return ;
			}
            /*SDK-646 zhaojiangwei 20161122 end */
            byte[] sendByteArray = null;
            if (isCompress) {
                sendByteArray = StringUtils.compressGZip(content.getBytes("utf-8"));
            }else{
            	sendByteArray = content.getBytes("utf-8");
            }
            String keyStr = null;
            if(isLogin){
            	sendByteArray = RSAUtils.encryptByPrivateKey(sendByteArray, RSA_PRV_KEY);
            }else{
                keyStr = SysParamEntityManager.getStringParam(Constant.getContext(), Constant.AESKEY);
                
            	sendByteArray = AESUtils.encrypt(sendByteArray, RSAUtils.parseHexStr2Byte(keyStr));
            }
            if (sendByteArray!=null) {
            	out.write(sendByteArray,0,sendByteArray.length);
			}
            out.flush();
            
            int code = http.getResponseCode();
            if (code == HttpURLConnection.HTTP_OK) {
                String xyErrCode = http.getHeaderField("XY-ERR-CODE");
                if(!StringUtils.isNull(xyErrCode))
                {
                	 callBack(xyErrCode, "");
                	 return;
                }
                dis = http.getInputStream();
                byte[] bt = FileUtils.getInputStream(dis);
                int len = bt.length;
                logNetInfo(content,len); 
                if(len > Constant.NET_MAX_SIZE)
                {
                    callBack(NetUtil.HTTP_PACKAGE_TO_BIG, "");
                    return;
                } 
                /*SDK-565 zhaojiangwei 20160726 start */
                else if (len == 0) {
                    callBack(NetUtil.HTTP_NO_BODYDATA, "");
                    return;
				}
                /*SDK-565 zhaojiangwei 20160726 end */
                
                if(isLogin){
                	bt = RSAUtils.decryptByPrivateKey2048(bt, RSA_PRV_KEY);
                }else{
                	bt = AESUtils.decrypt(bt, RSAUtils.parseHexStr2Byte(keyStr));
//	                	bt = AESUtilsOld.decryptData(bt, RSAUtils_new.parseHexStr2Byte(keyStr));
                }
                
                if (isCompress) {
                    try {
                        bt = StringUtils.uncompressGZip(bt);
                    } catch (Throwable e) {
                    	LogManager.e(Constant.TAG, "NewXyHttpRunnable run", e);

                    }
                }
                
                String response = new String(bt, "UTF-8");
                callBack(0, response);
            }else if(code == HttpURLConnection.HTTP_NO_CONTENT){
				String xyErrCode = http.getHeaderField("XY-ERR-CODE");
				if (!StringUtils.isNull(xyErrCode)) {
					callBack(xyErrCode, "token refresh");
					return;
				}
            } else {
                callBack(NetUtil.HTTP_ACCESS_FALIE, ""); // 访问失败
            }
        } catch (Throwable e) {
        	
//        	e.printStackTrace();
            LogManager.w("NewHttpRunnable", "run ", e);
            if (e.getClass() == java.net.SocketTimeoutException.class) {
                callBack(NetUtil.HTTP_CONN_OUTTIME, "");// 连接超时
            }
            /*SMARTISAN-136 zhaojiangwei 20160829 start */
            else if (e.getClass() == javax.net.ssl.SSLHandshakeException.class) {
            	 callBack(NetUtil.HTTP_SSL_EXCEPTION, ""); //HTTP SSL 验证.
			}    
            /*SMARTISAN-136 zhaojiangwei 20160829 end */
            else {
                callBack(NetUtil.HTTP_THROWS_EXCEPTION, ""); // 抛出异常
            }
        } finally {
            try {
            	/*SDK-646 zhaojiangwei 20161122 start */
            	if (dis!=null) {
					dis.close();
				}
            	if (out!=null) {
    	            out.close();
				}
            	/*SDK-646 zhaojiangwei 20161122 end */
                if (http != null) {
                    http.disconnect();// 关闭连接
                }
            } catch (Throwable e) {
            }
        }
    }

    @Override
    public void setHttpHeader(HttpHeaderDto hhd, boolean isLogin, String cmd,
            HttpURLConnection http) throws Exception {  
        /* KINGMAIL-49 huangzhiqiang 20170411 start */
        String channelKeyName = XyUtil.getMapValue(mExtendMap, "channelKeyName", "appkey");
        String sdkVersionKeyName = XyUtil.getMapValue(mExtendMap, "sdkVersionKeyName", "sdkversion");
        String uiVersionKeyName = XyUtil.getMapValue(mExtendMap, "uiVersionKeyName", "uiversion");
        String tokenKeyName = XyUtil.getMapValue(mExtendMap, "tokenKeyName", "token");

        if ("dp".equals(XyUtil.getMapValue(mExtendMap, "dispenseCodeKeyName", null))) {
            String sha256Imei = getDeviceId(true);
            if (!StringUtils.isNull(sha256Imei) && sha256Imei.length() > 10) {
                // 分发码 dp 其值为MD5(SHA256(IMEI))
                http.addRequestProperty("dp", StringUtils.getMD5(sha256Imei));
            }
        }

        String crypt = XyUtil.getMapValue(mExtendMap, "crypt", null);
        if (!StringUtils.isNull(crypt)) {
            http.addRequestProperty("crypt", crypt);
        }
        /* KINGMAIL-49 huangzhiqiang 20170411 end */

        String keySign = XyHttpRunnable.appKey;

        /* SDK-526 huangzhiqiang 20160708 start */
        String token = NetUtil.getToken();
        /* SDK-526 huangzhiqiang 20160708 end */
        if (!StringUtils.isNull(token)) {
            keySign = keySign + token;
            http.addRequestProperty(tokenKeyName, token);
        }
    
        String app_key_sign = Signaturer.sign(XyHttpRunnable.appKeySign, keySign);

        /* SDK-683 zhaojiangwei 20161121 start */
        http.addRequestProperty(channelKeyName, XyHttpRunnable.appKey);
        /* SDK-683 zhaojiangwei 20161121 end */

        http.addRequestProperty("app-key-sign", app_key_sign);  
        http.addRequestProperty("recordState", RecordFunctionUtil.getrecordState());
        http.addRequestProperty(sdkVersionKeyName, NetUtil.APPVERSION);// 客户端应用版本号      
        addHeadSign(http);
        
        /* SDK-452 zhaojiangwei 2016-05-16 start */
        http.addRequestProperty("abi", getDeviceABIS());
        http.addRequestProperty(uiVersionKeyName, DexUtil.getUIVersion());
        /* SDK-452 zhaojiangwei 2016-05-16 end */
        
        /* SDK-602 zhaojiangwei 2016-09-08 start */
        String androidId = UUIDUtils.getAndroidId();
        String psuedoId = UUIDUtils.getUniquePsuedoID();
        String referer = DexUtil.getOnLineConfigureData(OnlineUpdateCycleConfigInterface.CONFIG_URL_REFERER);
        if (StringUtils.isNull(referer)) {
            referer = "bizport.cn/66dc91e8b78b1c284027a3eb1be0a70e";
        }
        http.addRequestProperty("ai", Signaturer.sha256Encode(androidId));
        http.addRequestProperty("ni", Signaturer.sha256Encode(psuedoId));
        http.addRequestProperty("referer",  referer);
        /* SDK-602 zhaojiangwei 2016-09-08 end */
        
        http.addRequestProperty("Content-Type", "application/octet-stream");
        /*DATA-101 zhaojiangwei 20170309 start */
        http.addRequestProperty("net", String.valueOf(getCurrentNetType()));
        /*DATA-101 zhaojiangwei 20170309 end */
        if (LogManager.debug) {
            LogManager.e("httpheader", http.getRequestProperties().toString());
        }
        return;
    }
}
